<?php

class SJB_Admin_Users_Users extends SJB_Function
{
	public function isAccessible()
	{
		$this->setPermissionLabel('manage_users');
		return parent::isAccessible();
	}

	public function execute()
	{
		$tp = SJB_System::getTemplateProcessor();

		$page = 1;
		if (!empty($_REQUEST["page"]))
			$page = intval($_REQUEST["page"]);
		$items_per_page = SJB_Request::getVar('users_per_page', 50);
		$errors = array();
		/********** A C T I O N S   W I T H   U S E R S **********/
		$action = SJB_Request::getVar('action_name');

		if (!empty($action)) {
			$users_sids = SJB_Request::getVar('users', array());
			$_REQUEST['restore'] = 1;

			switch ($action) {

				case  'approve':
					foreach ($users_sids as $user_sid => $value) {
						$username = SJB_UserManager::getUserNameByUserSID($user_sid);
						SJB_UserManager::setApprovalStatusByUserName($username, 'Approved');
						SJB_UserManager::activateUserByUserName($username);
						SJB_UserDBManager::deleteActivationKeyByUsername($username);
						$password_original = SJB_UserManager::getPasswordOriginalByUserName($username);

						if ($password_original != null && !SJB_SocialPlugin::getProfileSocialID($user_sid)) {
							SJB_Notifications::sendUserWelcomeLetter($user_sid, $password_original);
							SJB_UserManager::setPasswordOriginalByUserName($username);
						} else {
							SJB_Notifications::sendUserApprovedLetter($user_sid);
						}
					}
					break;

				case  'reject':
					$rejection_reason = SJB_Request::getVar('rejection_reason', '');
					foreach ($users_sids as $user_sid => $value) {
						$username = SJB_UserManager::getUserNameByUserSID($user_sid);
						SJB_UserManager::setApprovalStatusByUserName($username, 'Rejected', $rejection_reason);
						SJB_UserManager::deactivateUserByUserName($username);
						SJB_Notifications::sendUserRejectedLetter($user_sid);
					}
					break;

				case  'activate':
					foreach ($users_sids as $user_sid => $value) {
						$username = SJB_UserManager::getUserNameByUserSID($user_sid);
						$userinfo = SJB_UserManager::getUserInfoByUserName($username);
						SJB_UserManager::activateUserByUserName($username);
						if ($userinfo['approval'] == 'Approved') {
							SJB_UserDBManager::deleteActivationKeyByUsername($username);
							SJB_Notifications::sendUserApprovedLetter($user_sid);
						}
					}
					break;

				case 'deactivate':
					foreach ($users_sids as $user_sid => $value) {
						$username = SJB_UserManager::getUserNameByUserSID($user_sid);
						SJB_UserManager::deactivateUserByUserName($username);
					}
					break;

				case 'delete':
					foreach ($users_sids as $user_sid => $value) {
						$username = SJB_UserManager::getUserNameByUserSID($user_sid);
						SJB_UserManager::deleteUserByUserName($username);
					}
					break;

				case 'send_activation_letter':
					foreach ($users_sids as $user_sid => $value)
						SJB_Notifications::sendUserActivationLetter($user_sid);
					break;

				case 'change_product':
					$productToChange = SJB_Request::getVar('product_to_change');
					
					if ( empty($productToChange) )
						$productToChange = 0;
					foreach ( $users_sids as $user_sid => $value ) {
						$user = SJB_UserManager::getObjectBySID($user_sid);
						// UNSUBSCRIBE selected
						if ($productToChange == 0) {
							SJB_ContractManager::deleteAllContractsByUserSID($user_sid);
						} else {
							$listingNumber = SJB_Request::getVar('number_of_listings', null);
							$productInfo = SJB_ProductsManager::getProductInfoBySID($productToChange);
							$listingNumber = $listingNumber?$listingNumber:!empty($productInfo['number_of_listings'])?$productInfo['number_of_listings']:null;
							$contract = new SJB_Contract(array('product_sid' => $productToChange, 'numberOfListings' => $listingNumber, 'is_recurring' => 0));
							$contract->setUserSID($user_sid);
							$contract->saveInDB();
						}
					}
					break;
					
				case 'ban_ip':
					$cantBanUsers = array();
					foreach ($users_sids as $user_sid => $value) {
						$user = SJB_UserManager::getUserInfoBySID($user_sid);
						if ($user['ip'] && !SJB_IPManager::getBannedIPByValue($user['ip']))
							SJB_IPManager::makeIPBanned($user['ip']);
						else
							$cantBanUsers[] = $user['username'];
					}
					$tp->assign('cantBanUsers', $cantBanUsers);
					break;

				case 'unban_ip':
					$cantUnbanIPs = array();
					foreach ($users_sids as $user_sid => $value) {
						$user = SJB_UserManager::getUserInfoBySID($user_sid);
						if ($user['ip'] !== '') {
							if (SJB_IPManager::getBannedIPByValue($user['ip']))
								SJB_IPManager::makeIPEnabledByValue($user['ip']);
							elseif (SJB_UserManager::checkBan($errors, $user['ip']))
								$cantUnbanIPs[] = $user['ip'];
						}
					}
					if ($cantUnbanIPs)
						$tp->assign('rangeIPs', $cantUnbanIPs);
					break;

				default:
					unset($_REQUEST['restore']);
					break;
			}
		}

		/***************************************************************/

		$_REQUEST['action'] = 'search';

		$user = new SJB_User();

		$user->addProperty(array
			(
				'id' => 'user_group',
				'type' => 'list',
				'value' => '',
				'is_system' => true,
				'list_values' => SJB_UserGroupManager::getAllUserGroupsIDsAndCaptions()
			)
		);

		$user->addProperty(array
			(
				'id' => 'registration_date',
				'type' => 'date',
				'value' => '',
				'is_system' => true
			)
		);
		$user->addProperty(array(
				'id' => 'approval',
				'caption' => 'Approval',
				'type' => 'list',
				'list_values' => array(
					array(
						'id' => 'Pending',
						'caption' => 'Pending',
					),
					array(
						'id' => 'Approved',
						'caption' => 'Approved',
					),
					array(
						'id' => 'Rejected',
						'caption' => 'Rejected',
					)
				),
				'length' => '10',
				'is_required' => false,
				'is_system' => true,
			)
		);

		// get array of accessible products
		$products = SJB_ProductsManager::getAllProductsInfo();
		foreach ($products as $key => $product) {
			if (!empty($product['pricing_type']) && $product['pricing_type'] == 'volume_based' && !empty($product['volume_based_pricing'])) {
				$volumeBasedPricing = $product['volume_based_pricing'];
				$minListings = min($volumeBasedPricing['listings_range_from']);
				$maxListings = max($volumeBasedPricing['listings_range_to']);
				$countListings = array();
				for ($i = $minListings; $i <= $maxListings; $i++)
					$countListings[] = $i;
				$products[$key]['count_listings'] = $countListings;
			}
		}

		$user->addProperty(array
			(
				'id' => 'product',
				'type' => 'list',
				'value' => '',
				'list_values' => $products,
				'is_system' => true
			)
		);

		$aliases = new SJB_PropertyAliases();

		$aliases->addAlias(array(
				'id' => 'user_group',
				'real_id' => 'user_group_sid',
				'transform_function' => 'SJB_UserGroupManager::getUserGroupSIDByID'
			)
		);

		$aliases->addAlias(array(
				'id' => 'product',
				'real_id' => 'product_sid',
			)
		);

		$search_form_builder = new SJB_SearchFormBuilder($user);
		$criteria_saver = new SJB_UserCriteriaSaver();

		if (isset($_REQUEST['restore']))
			$_REQUEST = array_merge($_REQUEST, $criteria_saver->getCriteria());

		$criteria = $search_form_builder->extractCriteriaFromRequestData($_REQUEST, $user);

		$search_form_builder->setCriteria($criteria);
		$search_form_builder->registerTags($tp);
		if (SJB_Request::getVar('online', '') == '1')
			$tp->assign("online", true);
		$tp->assign('products', $products);
		$tp->assign('selectedProduct', isset($_REQUEST['product']['simple_equal']) ? $_REQUEST['product']['simple_equal'] : '');
		$tp->display("user_search_form.tpl");

		/********************** S O R T I N G *********************/

		$sorting_field = SJB_Request::getVar('sorting_field', 'registration_date');
		$sorting_order = SJB_Request::getVar('sorting_order', 'DESC');
		$inner_join = false;

		// if search by product field
		if (isset($_REQUEST['product']['simple_equal']) && $_REQUEST['product']['simple_equal'] != '') {
			switch ($sorting_field) {
				case 'user_group':
					$inner_join = array('user_groups' => array('sort_field' => 'id', 'join_field' => 'sid', 'join_field2' => 'user_group_sid', 'join' => 'INNER JOIN'),
						'contracts' => array('join_field' => 'user_sid', 'join_field2' => 'sid', 'join' => 'INNER JOIN'));
					break;
				default:
					$inner_join = array('contracts' => array('join_field' => 'user_sid', 'join_field2' => 'sid', 'join' => 'INNER JOIN'));
					break;
			}
		}
		else {
			switch ($sorting_field) {
				case 'user_group':
					$inner_join = array('user_groups' => array('sort_field' => 'id', 'join_field' => 'sid', 'join_field2' => 'user_group_sid', 'join' => 'INNER JOIN'));
					break;
			}
		}

		if (SJB_Request::getVar('online', '') == '1') {
			$maxLifeTime = ini_get("session.gc_maxlifetime");
			$currentTime = time();
			$innerJoinOnline = array(
				'user_session_data_storage' => array(
					'join_field' => 'user_sid',
					'join_field2' => 'sid',
					'select_field' => 'session_id',
					'join' => 'INNER JOIN',
					'where' => "AND unix_timestamp(`user_session_data_storage`.`last_activity`) + {$maxLifeTime} > {$currentTime}"));
			if ($inner_join)
				$inner_join = array_merge($inner_join, $innerJoinOnline);
			else
				$inner_join = $innerJoinOnline;
		}
		$searcher = new SJB_UserSearcher(array('limit' => ($page - 1) * $items_per_page, 'num_rows' => $items_per_page), $sorting_field, $sorting_order, $inner_join);

		$found_users = array();
		$found_users_sids = array();

		if (SJB_Request::getVar('action', '') == 'search') {
			$found_users = $searcher->getObjectsSIDsByCriteria($criteria, $aliases);
			$criteria_saver->setSession($_REQUEST, $searcher->getFoundObjectSIDs());
		} elseif (isset($_REQUEST['restore'])) {
			$found_users = $criteria_saver->getObjectsFromSession();
		}
		foreach ($found_users as $id => $userID) {
			$user_info = SJB_UserManager::getUserInfoBySID($userID);
			$user_group_id = SJB_UserGroupManager::getUserGroupNameBySID($user_info['user_group_sid']);
			if (SJB_UserManager::checkBan($errors, $user_info['ip']))
				$user_info['ip_is_banned'] = 1;
			$contractInfo = SJB_ContractManager::getAllContractsInfoByUserSID($user_info['sid']);
			if ($contractInfo) {
				foreach ($contractInfo as $key => $contract) {
					$productInfo = SJB_ProductsManager::getProductInfoBySID($contract['product_sid']);
					$user_info['product'][$key]['name'] = $productInfo['name'];
					$user_info['product'][$key]['contract_id'] = $contract['id'];
					$user_info['product'][$key]['sid'] = $productInfo['sid'];
				}
			}
			else
				$user_info['product'] = '';

			$user_info['user_group'] = $user_group_id;
			$found_users[$id] = $user_info;
		}

		$usersCount = $searcher->getAffectedRows();
		$sorted_found_users_sids = $found_users_sids;

		/****************************************************************/

		$pages = array();
		for ($i = $page - 3; $i < $page + 3; $i++) {
			if ($i > 0)
				$pages[] = $i;
			if ($i * $items_per_page > $usersCount)
				break;
		}

		$totalPages = ceil($usersCount / $items_per_page);
		if (empty($totalPages))
			$totalPages = 1;

		if (array_search(1, $pages) === false)
			array_unshift($pages, 1);
		if (array_search($totalPages, $pages) === false)
			array_push($pages, $totalPages);

		$ApproveByAdminChecked = SJB_UserGroupManager::isApproveByAdminChecked();

		$tp->assign("ApproveByAdminChecked", $ApproveByAdminChecked);
		$tp->assign("currentPage", $page);
		$tp->assign("totalPages", $totalPages);
		$tp->assign("pages", $pages);
		$tp->assign("usersCount", $usersCount);
		$tp->assign("found_users", $found_users);
		$searchFields = '';
		foreach ($_REQUEST as $key => $val) {
			if (is_array($val)) {
				foreach ($val as $fieldName => $fieldValue)
					$searchFields .= "&{$key}[{$fieldName}]={$fieldValue}";
			}
		}
		$tp->assign("searchFields", $searchFields);
		$tp->assign("sorting_field", $sorting_field);
		$tp->assign("sorting_order", $sorting_order);
		$tp->assign("users_per_page", $items_per_page);
		$tp->assign("found_users_sids", $sorted_found_users_sids);
		$tp->display("users.tpl");
	}
}
